<!-- 文件配置详情 -->
<script lang="ts" setup>
import { computed, ref } from 'vue'
import type { IDbFormItem } from '@/types/global'
import DuiForm from '@/common-ui/dui-form/index.vue'
import { ENUM_USEABLE } from '@/config/enum'
import { FILE_CONFIG_USE_STATUS } from '../config/config'
import * as fileApi from '@/api/file'
import type { IFileConfig } from '../config/type'
import useNotic from '@/hooks/useNotic'

const emits = defineEmits(['refresh'])

defineProps({
  title: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  }
})
// 详情id
const infoId = ref('')
// 是否显示弹窗
const showDialog = ref(false)
const ruleFormRef = ref<InstanceType<typeof DuiForm>>()
// 表单配置
const formConfig = computed<IDbFormItem[]>(() => {
  return [
    { label: '参数名称', prop: 'name', type: 'input', required: true },
    {
      label: '状态',
      prop: 'isForbidden',
      type: 'radio',
      list: FILE_CONFIG_USE_STATUS,
      required: true
    },
    { label: '第三方接口', prop: 'thirdConfig', type: 'DbCodeJson' }
  ]
})
// 表单数据
const defaultData: IFileConfig = {
  channelId: '',
  name: '',
  isForbidden: ENUM_USEABLE['启用'],
  thirdConfig: ''
}
const formData = ref<IFileConfig>(JSON.parse(JSON.stringify(defaultData)))
/**
 * 初始化弹窗
 */
function init(data: any) {
  infoId.value = data?.id ?? ''
  const defaultForm = JSON.parse(JSON.stringify(defaultData as any))
  Object.keys(defaultForm).forEach((key) => {
    ;(formData.value as any)[key] = data[key] ?? defaultForm[key]
  })
  showDialog.value = true
}
/**
 * 点击提交
 */
function submitClick() {
  ruleFormRef.value
    ?.validate()
    .then(() => {
      let reqFunc = fileApi.addFileConfig
      let params: any = formData.value
      if (infoId.value) {
        reqFunc = fileApi.editFileConfig
        params = { ...formData.value, id: infoId.value }
      }
      reqFunc(params).then((res) => {
        if (res.success) {
          useNotic().success('提交成功')
          showDialog.value = false
          emits('refresh')
        }
      })
    })
    .catch(() => {})
}

defineExpose({
  init
})
</script>

<template>
  <dui-dialog v-model="showDialog" :title="title">
    <dui-form ref="ruleFormRef" :form-config="formConfig" :form-data="formData" :disabled="disabled" />
    <template #footer>
      <el-button @click="showDialog = false">取消</el-button>
      <el-button type="primary" @click="submitClick" v-if="!disabled"> 确定 </el-button>
    </template>
  </dui-dialog>
</template>
